#include "my_scene.h"
#include "utility.h"

const std::string kVertexShaderPath   = "D:\\project\\dtt_app\\shader\\test\\vertex.vert";
const std::string kFragmentShaderPath = "D:\\project\\dtt_app\\shader\\test\\fragment.frag";

const static float positionData[] = {
    -1.0f, 1.0f, 0.0f,
    -1.0f, -1.0f, 0.0f,
    1.0f, -1.0f, 0.0f,
    1.0f, 1.0f, 0.0f};

const static float colorData[] = {
     1.0f, 0.0f, 0.0f,
     0.0f, 1.0f, 0.0f,
     0.0f, 0.0f, 1.0f,
     0.5f, 0.5f, 0.5f};

const static unsigned int index[] = {
    0,3,1,2
};

MyScene::MyScene()
    : _pVertexBuffer(new BufferObject())
    , _pColorBuffer(new BufferObject())
    , _pTexCoordBuffer(new BufferObject())
    , _pIndexBuffer(new BufferObject())
{
}

void MyScene::init()
{
    try
    {
        glClearColor(1.0, 1.0, 1.0, 1.0);
        _program.addShaderFile(GPUProgram::Vertex, kVertexShaderPath);
        _program.addShaderFile(GPUProgram::Fragment, kFragmentShaderPath);
        _program.use();

        _program.printActiveAttributes();
        _program.printActiveUniforms();

        _pVertexBuffer->read(
            sizeof(positionData),
            PixelFormat::PF_RGB_32F,
            BufferObject::ARRAY,
            BufferObject::STATIC_DRAW,
            (const char*)positionData);

        _pColorBuffer->read(
            sizeof(colorData),
            PixelFormat::PF_RGB_32F,
            BufferObject::ARRAY,
            BufferObject::STATIC_DRAW,
            (const char*)colorData);

        _pIndexBuffer->read(
            sizeof(index),
            PixelFormat::PF_R_32U,
            BufferObject::ELEMENT_ARRAY,
            BufferObject::STATIC_DRAW,
            (const char*)index);

        _vao.addAttribArray(_program.getActiveAttribute("VertexPosition"), _pVertexBuffer);
        _vao.addAttribArray(_program.getActiveAttribute("VertexColor"), _pColorBuffer);

        _vao.bind();
        _pIndexBuffer->bind();

    }
    catch(std::exception& e)
    {
        Log::error(e.what());
        throw;
    }
}


void MyScene::onRender()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    _modelViewMatrix = glm::mat4(1.0);

    glm::mat4 mat = glm::lookAt(
        glm::vec3(0, 0, 3),
        glm::vec3(0, 0, 0),
        glm::vec3(0, 1, 0));

    _modelViewMatrix = mat * _modelViewMatrix;

    glm::mat4 mvp = _projectionMatrix * _modelViewMatrix;
    _program.setUniform("MVPMatrix", mvp);
    //glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    glDrawElements(GL_TRIANGLE_STRIP, 4, GL_UNSIGNED_INT, (GLvoid*)NULL);
}

void MyScene::onKeyboard( unsigned char key, int x, int y )
{
}

void MyScene::onMouseMove( int x, int y )
{
}

void MyScene::onMouseButtonEvent( int button, int state, int x, int y )
{
}

void MyScene::onSizeChanged( int iWidth, int iHeight )
{
    Scene::onSizeChanged(iWidth, iHeight);
}
